package com.shunwang.errors.engine.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shunwang.errors.engine.handler.Handler;
import com.shunwang.errors.engine.util.ThrowableUtil;

/**
 * @author hadoop20
 * @version 1.0
 * @created 19-10-2011 10:40:55
 */
public class ErrorsHandler {

	private Logger logger = LoggerFactory.getLogger(ErrorsHandler.class);
	
	private Mapper mapper ;
	
	private boolean hasThrowable = true;

	public Mapper getMapper() {
		return mapper;
	}

	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}

	public boolean isHasThrowable() {
		return hasThrowable;
	}

	public void setHasThrowable(boolean hasThrowable) {
		this.hasThrowable = hasThrowable;
	}

	public void doHandler(Throwable throwable,Object... params) throws Throwable{
		String fullName = ThrowableUtil.getFirstThrowable(throwable);
		Mapping mapping = mapper.getMapping(fullName);
		if(mapping == null){
			doThrowable(throwable,fullName+" not mapping");
		}
		Handler handler = mapping.getHandler(throwable);
		if(handler == null){
			doThrowable(throwable,fullName+" not handler");
		}
		try{
			handler.doHandler(throwable, params);
		}catch(Exception e){
			doThrowable(e,e.getMessage());
		}
	}
	
	private void doThrowable(Throwable throwable,String msg) throws Throwable{
		logger.debug(msg);
		if(hasThrowable){
			throw throwable;
		}
	}

}